package config

import (
	"encoding/json"
	"os"
)

type Config struct {
	TunName    string `json:"tun_name"`
	PrivateKey string `json:"private_key"`
	Address    string `json:"address"`
	ListenPort int    `json:"listen_port"`
	PostUp     string `json:"post_up"`
	PostDown   string `json:"post_down"`
	Mtu        int    `json:"mtu"`

	Peers []struct {
		PublicKey           string   `json:"public_key"`
		Endpoint            string   `json:"endpoint"`
		AllowedIPs          []string `json:"allowed_ips"`
		PreSharedKey        string   `json:"pre_shared_key"`
		PersistentKeepalive uint32   `json:"persistentKeepalive"`
	} `json:"peers"`
}

func LoadConfig(path string) (*Config, error) {
	file, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}

	var config Config
	if err := json.Unmarshal(file, &config); err != nil {
		return nil, err
	}

	// Set defaults if not specified
	if config.Address == "" {
		config.Address = "10.0.0.1"
	}

	if config.TunName == "" {
		config.TunName = "tun0"
	}

	if config.Mtu == 0 {
		config.Mtu = 1420
	}
	return &config, nil
}
